package com.pd.backend.service.net.impl;

import com.pd.backend.domain.LoginUser;
import com.pd.backend.domain.entity.DGlobalUser;
import com.pd.backend.ex.CustomerException;
import com.pd.backend.service.net.LoginService;
import com.pd.backend.service.net.TokenService;
import com.pd.backend.service.net.UserService;
import com.pd.backend.common.utils.StringUtils;
import com.pd.backend.common.utils.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 登录业务层实现类
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserService userService;


    /**
     * 登录
     *
     * @param account  账号
     * @param password 密码
     * @param code     验证码
     * @param key      唯一标识
     * @return
     */
    @Override
    public String login(String account, String password, String code, String key) {
        // 处理参数 进行非空判断
        if (StringUtils.isEmpty(account)){
            throw new CustomerException("账号不能为空");
        }
        if (StringUtils.isEmpty(password)){
            throw new CustomerException("密码不能为空");
        }
        if (StringUtils.isEmpty(code)){
            throw new CustomerException("验证码不能为空");
        }
        if (StringUtils.isEmpty(key)){
            throw new CustomerException("唯一标识为空");
        }

        // 验证码 redis key
        String verifyKey = "captcha_codes:" + key;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (StringUtils.isEmpty(captcha)) {
            // TODO Contants
            throw new CustomerException("验证码失效");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            // TODO Contants
            throw new CustomerException("验证码错误");
        }
        // 登录验证
        log.info("account:{},password:{}",account,password);
        DGlobalUser dGlobalUser = userService.getUserByAccount(account);
        String dbAccount = dGlobalUser.getAccount();
        String dbPassword = dGlobalUser.getPassword();
        if (Objects.isNull(dGlobalUser)){
            // 账号不存在
            throw new CustomerException("账号不存在或输入有误");
        }
        if (!password.equals(dbPassword)){
            // 密码错误
            throw new CustomerException("密码错误");
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(dGlobalUser);

        // 登录成功 将用户信息存入redis 有效期30分钟
        redisCache.setCacheObject("login_user:",dGlobalUser,30, TimeUnit.MINUTES);
        // 生成tonken
        return tokenService.createToken(loginUser);
    }

}
